home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / ProgramD2.iso / Borland / Borland C++ V5.02 / THREADS.PAK / THREAD.CPP < prev    next >
C/C++ Source or Header  |  1997-05-06  |  2KB  |  90 lines

  1. // ---------------------------------------------------------------------------
  2. // Copyright (C) 1994 Borland International
  3. // thread.cpp
  4. //    Demonstrates the container class libraries' implementation
  5. //    of TThread and TCriticalSection.
  6. //    It also uses the WINNT's signalling of events to handle
  7. //    synchronization.
  8. // ---------------------------------------------------------------------------
  9. #include <classlib/thread.h>
  10. #include <winsys/wsysinc.h>
  11. #include <iostream.h>
  12.  
  13. // prevent cout from being interrupted
  14. TCriticalSection CS;
  15.  
  16. // prevent process thread from ending too soon
  17. const int NumThreads = 2;
  18. HANDLE Events[NumThreads];
  19.  
  20. //
  21. // class Thread
  22. //
  23. class Thread : public TThread
  24. {
  25.   public:
  26.     Thread( int id) : Id(id), Count(0) {}
  27.  
  28.   private:
  29.     int Run();
  30.     int Id;
  31.     int Count;
  32. };
  33.  
  34. int Thread::Run()
  35. {
  36.     while (Count++ < 10)
  37.         {
  38.         Sleep(100);         // let other thread have some time
  39.         // don't let cout be interrupted
  40. //        TCriticalSection::Lock lock(CS);
  41.         cout << "[Thread" << Id << "] Iteration " << Count << endl;
  42.         }
  43.     SetEvent(Events[Id]);   // Tell main thread I'm done
  44.     return 0;
  45. }
  46.  
  47. int main()
  48. {
  49.     try {
  50.         int i;
  51.         DWORD ErrCode;
  52.  
  53.         for (i=0; i<NumThreads; i++)
  54.             {
  55.             Events[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
  56.             if( Events[i] == NULL )
  57.                 throw(GetLastError());
  58.             }
  59.  
  60.         // create threads
  61.         Thread a(0);
  62.         Thread b(1);
  63.  
  64.         // start the threads
  65.         a.Start();
  66.         b.Start();
  67.  
  68.         // change priority of threads
  69.         a.SetPriority(THREAD_PRIORITY_NORMAL);
  70.         b.SetPriority(THREAD_PRIORITY_ABOVE_NORMAL);
  71.  
  72.         // threads have now started, wait until they're done.
  73.         ErrCode = WaitForMultipleObjects(NumThreads, Events, TRUE, INFINITE);
  74.         if( ErrCode == DWORD(-1) )
  75.             throw(GetLastError());
  76.  
  77.         // here if done.
  78.         for( i=0; i<NumThreads; i++ )
  79.             CloseHandle(Events[i]);
  80.  
  81.         cout << "Finished!" << endl;
  82.         }
  83.     catch (DWORD ErrCode)
  84.         {
  85.         // if any error
  86.         cout << "Errcode = " << ErrCode << endl;
  87.         }
  88.     return 0;
  89. }
  90.